package xyj.sparrow.scheduler.server;

import xyj.sparrow.common.connect.SparrowConnect;
import xyj.sparrow.common.netty.bean.Request;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import xyj.sparrow.scheduler.conf.SparrowSnowflake;
import xyj.sparrow.scheduler.server.connect.ConnectManager;
import xyj.sparrow.scheduler.service.ITaskLogService;
import xyj.sparrow.scheduler.util.ApplicationContextUtil;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 江南小俊
 * @since 2021-06-15 11:48
 **/
@Slf4j
public class ClientManager {
    private static final ITaskLogService iTaskLogService = ApplicationContextUtil.getBean(ITaskLogService.class);
    private static final SparrowSnowflake snowflake = ApplicationContextUtil.getBean(SparrowSnowflake.class);
    /**
     * 存储任务和远程的方法实现类的关系
     **/
    private static final ConcurrentHashMap<String, String> taskClassMap = new ConcurrentHashMap<>();

    public static void addTaskClass(String taskId, String className) {
        taskClassMap.put(taskId, className);
    }


    public static void scheduling(String appId, String taskId, LocalDateTime now) {
        ConnectManager connectManager = ApplicationContextUtil.getBean(ConnectManager.class);
        List<SparrowConnect> connects = connectManager.getConnect(appId);
        if (connects.isEmpty()) {
            log.info("没有客户端连接可供调度");
            return;
        }
        String className = taskClassMap.get(taskId);
        if (StrUtil.isBlank(className)) {
            String logId = snowflake.snowflakeId() + "";
            iTaskLogService.logError(logId, appId, taskId, "没有可用的客户端", now);
            log.error("没有可用的客户端");
            return;
        }
        for (SparrowConnect connect : connects) {
            String logId = snowflake.snowflakeId() + "";
            Channel next = connect.getChannel();
            iTaskLogService.logStart(logId, appId, taskId,
                    connect.getConnectDesc(),
                    now);
            Request request = new Request();
            request.setRequestId(IdUtil.simpleUUID());
            request.setClassName(className);
            request.setMethodName("start");
            Object[] objects = new Object[2];
            String[] strings = new String[2];
            strings[0] = connect.getConnectIndex() + "";
            strings[1] = connect.getConnectTotal() + "";
            objects[0] = logId;
            objects[1] = strings;
            request.setParams(objects);//存logId
            Class[] paramTypes = new Class[2];
            paramTypes[0] = String.class;
            paramTypes[1] = String[].class;
            request.setParamTypes(paramTypes);

            next.writeAndFlush(request);
        }
    }
}
